#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
智能出行规划HTTP服务器 - 模拟数据演示版
完全基于模拟数据，无需真实API
"""

import http.server
import socketserver
import json
import urllib.parse
from urllib.parse import urlparse, parse_qs
import webbrowser
import os
import requests
import random
from datetime import datetime, timedelta

# 导入智能规划器
from demo_travel_planner import SmartTripPlanner

PORT = 5000

class DemoHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        # 将根路径映射到前端页面
        if self.path in ['/', '/index', '/index.html']:
            self.path = '/frontend/index.html'
        elif self.path == '/favicon.ico':
            return self.send_error(404)
        if self.path.startswith('/api/'):
            self.handle_api_request()
        else:
            super().do_GET()
    
    def do_POST(self):
        if self.path.startswith('/api/'):
            self.handle_api_post()
        else:
            super().do_POST()
    
    def do_OPTIONS(self):
        # 处理CORS预检请求
        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        self.send_header('Access-Control-Max-Age', '86400')
        self.end_headers()
    
    def handle_api_request(self):
        if self.path == '/api/cities':
            self.send_cities()
        elif self.path == '/api/test':
            self.send_test()
        elif self.path == '/api/status':
            self.send_status()
        elif self.path.startswith('/api/weather'):
            self.send_weather()
        else:
            self.send_error(404)
    
    def handle_api_post(self):
        content_length = int(self.headers.get('Content-Length', 0) or 0)
        post_data = self.rfile.read(content_length) if content_length > 0 else b'{}'
        
        try:
            data = json.loads(post_data.decode('utf-8') or '{}')
            if self.path == '/api/search':
                self.send_smart_search_result(data)
            elif self.path == '/api/chat':
                self.send_chat_response(data)
            elif self.path == '/api/poi':
                self.send_poi(data)
            elif self.path == '/api/geocode':
                self.send_geocode(data)
            elif self.path == '/api/weather':
                self.send_weather(data)
            else:
                self.send_error(404)
        except Exception as e:
            self.send_json_response({'success': False, 'error': f'请求解析失败: {e}'})
    
    def send_cities(self):
        cities = [
            '北京', '上海', '广州', '深圳', '南京', '杭州',
            '成都', '武汉', '西安', '重庆', '天津', '苏州',
            '大连', '合肥', '青岛', '济南', '沈阳', '长沙',
            '郑州', '石家庄', '太原', '呼和浩特', '长春', '哈尔滨',
            '昆明', '贵阳', '南宁', '海口', '兰州', '西宁',
            '银川', '乌鲁木齐', '拉萨'
        ]
        response = {
            'success': True,
            'cities': [{'id': i + 1, 'name': c, 'code': '', 'level': 'city'} for i, c in enumerate(cities)]
        }
        self.send_json_response(response)
    
    def _categorize_route(self, route):
        """分类路线"""
        details = route.get('details', [])
        transfers = route.get('transfers', 0)
        
        if not details:
            return '其他'
        
        # 检查交通方式
        transport_types = [detail.get('type') for detail in details]
        
        # 直达航班
        if transfers == 0 and 'flight' in transport_types:
            return '直达航班'
        
        # 中转航班
        if transfers > 0 and all(t == 'flight' for t in transport_types):
            return '中转航班'
        
        # 直达高铁
        if transfers == 0 and 'high_speed_rail' in transport_types:
            return '直达高铁'
        
        # 中转高铁
        if transfers > 0 and all(t in ['high_speed_rail', 'train'] for t in transport_types):
            return '中转高铁'
        
        # 多式联运（混合交通方式）
        if len(set(transport_types)) > 1:
            return '多式联运'
        
        return '其他'
    
    def send_test(self):
        response = {
            'success': True,
            'message': '智能出行规划演示服务器正常运行！',
            'features': [
                '多式联运规划（模拟数据）',
                '智能中转建议', 
                '全局优化排序',
                '实时模拟交通数据',
                '智能推荐系统'
            ],
            'demo_mode': True
        }
        self.send_json_response(response)
    
    def send_status(self):
        response = {
            'success': True,
            'status': 'online',
            'version': '2.0.0-demo',
            'mode': 'demo',
            'apis': {
                'smart_planner': 'enabled',
                'multimodal': 'enabled',
                'transfer_optimization': 'enabled',
                'mock_data': 'enabled',
                'real_apis': 'disabled'
            }
        }
        self.send_json_response(response)
    
    def send_smart_search_result(self, data):
        """智能搜索主函数"""
        origin = data.get('origin', '北京')
        destination = data.get('destination', '上海')
        date = data.get('date') or data.get('departure_date')
        optimization_type = data.get('optimization_type', 'balanced')
        max_transfers = data.get('max_transfers', 2)
        
        print(f"🎯 智能搜索请求: {origin} → {destination} ({date})")
        
        try:
            # 创建规划器实例
            planner = SmartTripPlanner()
            
            # 转换优化类型参数
            preference_map = {
                'time': 'time',
                'cost': 'cost', 
                'comfort': 'comfort',
                'balanced': 'balanced',
                '时间优先': 'time',
                '价格优先': 'cost',
                '舒适度优先': 'comfort',
                '平衡优化': 'balanced'
            }
            
            preference = preference_map.get(optimization_type, 'balanced')
            
            # 调用智能规划器
            routes = planner.find_routes(
                from_city=origin,
                to_city=destination,
                preference=preference,
                max_transfers=max_transfers
            )
            
            # 转换为前端格式并按类别分组
            formatted_routes = []
            categorized_routes = {
                '直达航班': [],
                '中转航班': [],
                '直达高铁': [],
                '中转高铁': [],
                '多式联运': [],
                '其他': []
            }
            
            for route in routes:
                formatted_route = {
                    'total_time': route.total_duration,
                    'total_price': route.total_price,
                    'total_distance': route.total_distance,
                    'transfers': route.transfers,
                    'comfort_score': route.comfort_score,
                    'reliability_score': route.reliability_score,
                    'optimization_score': route.optimization_score,
                    'tags': route.tags,
                    'description': route.description,
                    'details': []
                }
                
                # 转换交通段详情
                for leg in route.legs:
                    detail = {
                        'type': leg.transport_type,
                        'origin': leg.from_city,
                        'destination': leg.to_city,
                        'departure_time': leg.departure_time,
                        'arrival_time': leg.arrival_time,
                        'duration': leg.duration,
                        'price': leg.price,
                        'distance': leg.distance,
                        'comfort_score': leg.comfort_score,
                        'reliability_score': leg.reliability_score,
                        'carrier': leg.carrier
                    }
                    
                    # 添加交通方式特定信息
                    if leg.transport_type == 'flight':
                        detail['flight_number'] = leg.carrier
                        detail['airline'] = leg.carrier[:2]
                    elif leg.transport_type in ['high_speed_rail', 'train']:
                        detail['train_number'] = leg.carrier
                        detail['seat_type'] = '二等座' if leg.transport_type == 'high_speed_rail' else '硬座'
                    
                    formatted_route['details'].append(detail)
                
                # 分类路线
                category = self._categorize_route(formatted_route)
                categorized_routes[category].append(formatted_route)
                formatted_routes.append(formatted_route)
            
            # 为每个类别添加统计信息
            category_stats = {}
            for category, routes_list in categorized_routes.items():
                if routes_list:
                    category_stats[category] = {
                        'count': len(routes_list),
                        'best_time': min(r.get('total_time', 0) for r in routes_list),
                        'best_price': min(r.get('total_price', 0) for r in routes_list),
                        'avg_comfort': sum(r.get('comfort_score', 0) for r in routes_list) / len(routes_list)
                    }
            
            response = {
                'success': True,
                'routes': formatted_routes,
                'categorized_routes': categorized_routes,
                'category_stats': category_stats,
                'message': f'智能规划为您找到 {len(formatted_routes)} 条最优路线（模拟数据）',
                'source': 'demo_smart_planner',
                'optimization_type': optimization_type,
                'demo_mode': True,
                'params': {
                    'origin': origin,
                    'destination': destination,
                    'date': date,
                    'max_transfers': max_transfers
                }
            }
            
            self.send_json_response(response)
            
        except Exception as e:
            print(f"智能搜索失败: {e}")
            self.send_json_response({
                'success': False,
                'error': f'智能规划失败: {e}',
                'routes': [],
                'message': '搜索失败，请重试'
            })
    
    def send_weather(self, data=None):
        """天气查询（模拟数据）"""
        if data:
            city = data.get('city', '北京')
        else:
            query_params = parse_qs(urlparse(self.path).query)
            city = query_params.get('city', ['北京'])[0]
        
        # 模拟天气数据
        weather_conditions = ['晴', '多云', '阴', '小雨', '中雨', '雪']
        temperatures = list(range(15, 30))
        
        response = {
            'success': True,
            'weather': {
                'city': city,
                'temperature': f'{random.choice(temperatures)}°C',
                'condition': random.choice(weather_conditions),
                'humidity': f'{random.randint(40, 80)}%',
                'wind': f'{random.choice(["北", "南", "东", "西"])}风 {random.randint(1, 4)}级'
            },
            'source': 'mock'
        }
        
        self.send_json_response(response)
    
    def send_poi(self, data):
        """POI搜索（真实地理位置）"""
        query = data.get('query', '')
        city = data.get('city', '北京')
        
        # 真实地理位置数据库
        real_locations = {
            '大连': {
                '大连交通大学': {'address': '辽宁省大连市沙河口区黄河路794号', 'location': '121.539,38.914'},
                '大连理工大学': {'address': '辽宁省大连市甘井子区凌工路2号', 'location': '121.544,38.887'},
                '大连火车站': {'address': '辽宁省大连市中山区长江路260号', 'location': '121.625,38.920'},
                '大连北站': {'address': '辽宁省大连市甘井子区南关岭街道', 'location': '121.601,39.004'},
                '大连周水子国际机场': {'address': '辽宁省大连市甘井子区迎客路100号', 'location': '121.539,38.965'},
                '大连港': {'address': '辽宁省大连市中山区港湾街1号', 'location': '121.650,38.920'},
                '星海广场': {'address': '辽宁省大连市沙河口区星海广场', 'location': '121.580,38.880'},
                '中山广场': {'address': '辽宁省大连市中山区中山广场', 'location': '121.625,38.920'}
            },
            '合肥': {
                '合肥南站': {'address': '安徽省合肥市包河区徽州大道', 'location': '117.280,31.800'},
                '合肥火车站': {'address': '安徽省合肥市瑶海区胜利路', 'location': '117.320,31.880'},
                '合肥新桥国际机场': {'address': '安徽省合肥市蜀山区高刘镇', 'location': '117.200,31.900'},
                '安徽大学': {'address': '安徽省合肥市蜀山区九龙路111号', 'location': '117.200,31.850'},
                '中国科学技术大学': {'address': '安徽省合肥市蜀山区金寨路96号', 'location': '117.250,31.850'},
                '合肥工业大学': {'address': '安徽省合肥市包河区屯溪路193号', 'location': '117.280,31.850'},
                '天鹅湖': {'address': '安徽省合肥市蜀山区天鹅湖', 'location': '117.200,31.820'},
                '包公园': {'address': '安徽省合肥市包河区芜湖路72号', 'location': '117.300,31.860'}
            },
            '北京': {
                '北京站': {'address': '北京市东城区毛家湾胡同甲13号', 'location': '116.420,39.900'},
                '北京西站': {'address': '北京市丰台区莲花池东路', 'location': '116.320,39.900'},
                '北京南站': {'address': '北京市丰台区永外大街12号', 'location': '116.380,39.870'},
                '首都国际机场': {'address': '北京市顺义区天竺镇', 'location': '116.600,40.080'},
                '北京大学': {'address': '北京市海淀区颐和园路5号', 'location': '116.300,39.990'},
                '清华大学': {'address': '北京市海淀区清华园1号', 'location': '116.330,40.000'},
                '天安门广场': {'address': '北京市东城区东长安街', 'location': '116.390,39.900'},
                '故宫博物院': {'address': '北京市东城区景山前街4号', 'location': '116.400,39.920'}
            },
            '上海': {
                '上海虹桥站': {'address': '上海市闵行区申贵路1500号', 'location': '121.320,31.200'},
                '上海站': {'address': '上海市静安区秣陵路303号', 'location': '121.450,31.250'},
                '浦东国际机场': {'address': '上海市浦东新区迎宾大道6000号', 'location': '121.800,31.150'},
                '复旦大学': {'address': '上海市杨浦区邯郸路220号', 'location': '121.500,31.300'},
                '上海交通大学': {'address': '上海市闵行区东川路800号', 'location': '121.430,31.020'},
                '外滩': {'address': '上海市黄浦区中山东一路', 'location': '121.490,31.240'},
                '东方明珠': {'address': '上海市浦东新区世纪大道1号', 'location': '121.500,31.240'},
                '南京路步行街': {'address': '上海市黄浦区南京东路', 'location': '121.480,31.240'}
            }
        }
        
        # 搜索匹配的地点
        pois = []
        city_locations = real_locations.get(city, {})
        
        for name, info in city_locations.items():
            if query.lower() in name.lower() or query.lower() in info['address'].lower():
                pois.append({
                    'name': name,
                    'address': info['address'],
                    'location': info['location']
                })
        
        # 如果没有找到匹配的，返回一些通用地点
        if not pois:
            for name, info in list(city_locations.items())[:3]:
                pois.append({
                    'name': name,
                    'address': info['address'],
                    'location': info['location']
                })
        
        response = {
            'success': True,
            'pois': pois,
            'source': 'real_locations'
        }
        
        self.send_json_response(response)
    
    def send_geocode(self, data):
        """地理编码（模拟数据）"""
        address = data.get('address', '')
        
        # 模拟地理编码数据
        response = {
            'success': True,
            'geocode': {
                'address': address,
                'location': '116.397,39.916',
                'formatted_address': f'{address}（模拟地址）'
            },
            'source': 'mock'
        }
        
        self.send_json_response(response)
    
    def send_chat_response(self, data):
        """AI聊天回复（模拟数据）"""
        message = data.get('message', '')
        if not message:
            self.send_json_response({'success': False, 'error': '请提供message'})
            return
        
        # 智能回复逻辑
        if '时间' in message or '几点' in message:
            now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            response_text = f'现在是 {now}（演示模式）'
        elif '天气' in message:
            response_text = '我是智能出行助手，可以帮您规划最优路线。天气查询功能正在开发中，请使用搜索功能查询出行方案！'
        elif '路线' in message or '出行' in message or '交通' in message:
            response_text = '我可以帮您规划智能出行路线！请在上方搜索框中输入出发地和目的地，我会为您提供多种交通方案，包括直达和中转选项。'
        elif '价格' in message or '费用' in message or '便宜' in message:
            response_text = '我会为您提供多种价格方案！系统会自动比较直达和中转路线的费用，帮您找到最经济的出行方式。'
        elif '时间' in message or '快' in message or '慢' in message:
            response_text = '我会为您优化出行时间！系统会综合考虑直达和中转方案，帮您找到最快的出行路线。'
        else:
            response_text = f'我理解您的问题："{message}"。作为智能出行助手，我可以帮您规划最优路线、查询交通信息、提供出行建议。请告诉我您的具体出行需求！'
        
        self.send_json_response({
            'success': True,
            'response': response_text,
            'model': 'demo_ai'
        })
    
    def send_json_response(self, data):
        """发送JSON响应"""
        self.send_response(200)
        self.send_header('Content-Type', 'application/json; charset=utf-8')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.end_headers()
        
        json_str = json.dumps(data, ensure_ascii=False, indent=2)
        self.wfile.write(json_str.encode('utf-8'))

if __name__ == '__main__':
    print("=" * 60)
    print("启动智能出行规划演示服务器")
    print("=" * 60)
    print(f"服务地址: http://localhost:{PORT}")
    print(f"测试地址: http://localhost:{PORT}/api/test")
    print(f"城市列表: http://localhost:{PORT}/api/cities")
    print(f"前端页面: http://localhost:{PORT}/frontend/index.html")
    print("=" * 60)
    print("演示模式：使用模拟数据，无需真实API")
    print("按 Ctrl+C 停止服务")
    print("=" * 60)

    # 关键：将工作目录切到脚本所在目录，确保能找到 frontend/index.html
    try:
        os.chdir(os.path.dirname(os.path.abspath(__file__)))
    except Exception as _e:
        pass
    
    with socketserver.TCPServer(("", PORT), DemoHTTPRequestHandler) as httpd:
        try:
            # 自动打开浏览器
            webbrowser.open(f"http://localhost:{PORT}/frontend/index.html")
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\n服务器已停止")